<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午9:25
 */


class SelfMemberService extends ServiceBase {

    /**
     * @return bool|string 失败返回false， 成功返回 $token／password
     */
    public function createMember(){
        $member = new Member();
        $userId = $this->getUniqueID();
        $token = $member->getSignature($userId);
        $member->name = $userId;
        $member->nick_name = '自助终端 No:'.substr($userId, 0, 8);
        $member->unique_id = $userId;
        $userInfo = $this->getUserInfo($userId, $token);

        if(!$member->validate()){
            $this->errors()->merge($member->errors());
            return false;
        }
        //create user
        $repo = App::make('UserRepository');
        $user = $repo->signup($userInfo);

        if (!$user->id) {
            $this->errors()->merge($user->errors());
            return false;
        }

        //create member
        if(!$member->save()){
            $this->errors()->merge($member->errors());
            return false;
        }
        //relate user and member
        $user->attach_id = $member->id;
        $user->attach_type = 'Member';
        $user->confirmed = 1;
        if(!$user->save()){
            $this->errors()->merge($user->errors());
            return false;
        }
        BLogger::getLogger(BLogger::LOG_REG_DEVICE)->info('Create Member From Self Service Device, UserID:'.$userId.', token:'.$token.'');
        return $userInfo;
    }

    public function getUserInfo($username, $token){
        $user_info = array();

        array_set($user_info, 'username', $username);
        array_set($user_info, 'email', substr($username, 0, 8).'@email.com');
        array_set($user_info, 'password', $token);
        array_set($user_info, 'password_confirmation', $token);
        return $user_info;
    }

    public function getUniqueID(){
        return md5(uniqid(mt_rand(), true));
    }


    /**
     * 自助终端身份认证
     * @param $userId
     * @param $token
     * @return bool
     */
    public function checkSignature($userId, $token){
        $member = new Member();
        $member->unique_id = $userId;
        return $member->checkSignature($token);
    }

    public function getRankingListForSettle($limit){

        return MemberAccountLog::groupBy('member_account_log.member_id')->select(DB::raw('members.id, members.name, sum(happen_money) as total_price'))
            ->join('members','members.id', '=', 'member_account_log.member_id')->orderBy('total_price', 'desc')->limit($limit)->get();
    }

}

